using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using TerritoryGame.Infrastructure.Data;
using TerritoryGame.Domain.Entities.App;
using System.Security.Claims;

namespace TerritoryGame.Api.Middleware
{
    public class UserActivityMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<UserActivityMiddleware> _logger;

        public UserActivityMiddleware(RequestDelegate next, ILogger<UserActivityMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context, TerritoryGameDbContext dbContext)
        {
            // 先执行下一个中间件
            await _next(context);

            // 检查是否是已认证用户且不是排除的路径
            if (context.User?.Identity?.IsAuthenticated == true &&
                context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/static", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/system/logs", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/files/preview", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/users/avatar-file", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/files/download", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    var userIdClaim = context.User.FindFirst("sub")?.Value
                        ?? context.User.FindFirst("user_id")?.Value
                        ?? context.User.FindFirst("uid")?.Value;

                    if (!string.IsNullOrEmpty(userIdClaim) && Guid.TryParse(userIdClaim, out var userId))
                    {
                        // 异步更新用户活动时间（避免DbContext并发问题）
                        _ = Task.Run(async () =>
                        {
                            try
                            {
                                // 使用新的DbContext实例避免并发问题
                                using var serviceScope = context.RequestServices.CreateScope();
                                using var newDbContext = serviceScope.ServiceProvider.GetRequiredService<TerritoryGameDbContext>();
                                
                                var user = await newDbContext.Users.FindAsync(userId);
                                if (user != null)
                                {
                                    user.LastActivityTime = DateTime.UtcNow;
                                    await newDbContext.SaveChangesAsync();
                                    _logger.LogDebug("更新用户 {UserId} 的活动时间为 {ActivityTime}", userId, user.LastActivityTime);
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "更新用户活动时间时发生错误，用户ID: {UserId}", userId);
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "处理用户活动时间更新时发生错误");
                }
            }
        }
    }
}
